package com.turbo.dialog;

import com.intellij.ide.IdeView;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.impl.file.PsiDirectoryImpl;
import com.turbo.service.impl.ProjectServiceImpl;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.*;

public class DemoDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField name;

    public DemoDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ProjectServiceImpl projectService = new ProjectServiceImpl();
                IdeView ideView = event.getRequiredData(LangDataKeys.IDE_VIEW);
                PsiDirectory orChooseDirectory = ideView.getOrChooseDirectory();
                // 获取当前鼠标点击的目录，以及表单参数
                String s = projectService.doSomething(event.getProject(), orChooseDirectory.getVirtualFile().getPresentableUrl(), name.getText());
                if (StringUtils.isNotBlank(s)){
                    onOK();
                }else {
                    onOK();
                    Messages.showErrorDialog("创建失败", "错误");
                }
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        // add your code here
        dispose();
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }

    private ActionListener listener;
    private AnActionEvent event;

    public void setListener(ActionListener listener) {
        this.listener = listener;
    }

    public void setEvent(AnActionEvent event) {
        this.event = event;
    }
}
